package com.lu.nio;

import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @program lu-netty
 * @description:
 * @author: zhanglu
 * @create: 2022-06-10 16:11:00
 */
public class ChannelHandler {

    private SocketChannel channel;
    private String charset;

    public ChannelHandler(SocketChannel channel, String charset) {
        this.channel = channel;
        this.charset = charset;
    }

    public void writeAndFlush(Object msg){
        try {
            byte[] bytes = msg.toString().getBytes(charset);
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            this.channel.write(writeBuffer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SocketChannel channel(){
        return this.channel;
    }

}
